<template>
  <a-row :gutter="24">
    <a-col :md="24">
      <a-card :style="cardStyle" :bordered="false">
        <!-- 上传区域 -->
        <div class="upload-section">
          <a-upload-dragger
            name="files"
            :multiple="true"
            :action="uploadUrl"
            :headers="headers"
            :fileList="fileList"
            :beforeUpload="beforeUpload"
            @change="handleUploadChange"
            accept="image/*"
            listType="picture"
          >
            <p class="ant-upload-drag-icon">
              <a-icon type="inbox" />
            </p>
            <p class="ant-upload-text">点击或拖拽入库单据图片到此处上传</p>
            <p class="ant-upload-hint">支持单次上传多张图片，系统将自动识别单据内容</p>
          </a-upload-dragger>
        </div>

        <!-- 识别结果展示区域 -->
        <div class="result-section" v-if="showResult">
          <a-divider orientation="left">AI识别结果（请核对修改）</a-divider>

          <!-- 基本信息 -->
          <a-form :form="form" layout="horizontal">
            <a-row :gutter="24">
              <a-col :md="8" :sm="24">
                <a-form-item label="单据编号" :labelCol="{span: 6}" :wrapperCol="{span: 18}">
                  <a-input
                    v-decorator="['billNumber', {rules: [{required: true, message: '请输入单据编号'}]}]"
                    placeholder="自动识别或手动输入"
                  />
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="供应商" :labelCol="{span: 6}" :wrapperCol="{span: 18}">
                  <a-select
                    v-decorator="['supplierId']"
                    showSearch
                    optionFilterProp="children"
                    placeholder="请选择供应商"
                  >
                    <a-select-option v-for="item in supplierList" :key="item.id" :value="item.id">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :md="8" :sm="24">
                <a-form-item label="入库日期" :labelCol="{span: 6}" :wrapperCol="{span: 18}">
                  <a-date-picker
                    v-decorator="['inboundDate']"
                    style="width: 100%"
                    format="YYYY-MM-DD"
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <!-- 商品明细表格 -->
            <div class="table-section">
              <a-table
                :columns="columns"
                :dataSource="form.getFieldValue('items') || []"
                :pagination="false"
                bordered
                size="middle"
              >
                <template slot="operation" slot-scope="text, record, index">
                  <a-popconfirm
                    title="确定删除此行吗?"
                    @confirm="() => removeItem(index)"
                  >
                    <a href="javascript:;" style="color: #ff4d4f">删除</a>
                  </a-popconfirm>
                </template>
              </a-table>
              <a-button
                style="width: 100%; margin-top: 16px"
                type="dashed"
                icon="plus"
                @click="addItem"
              >
                添加商品
              </a-button>
            </div>

            <!-- 操作按钮 -->
            <div class="action-buttons">
              <a-button type="primary" @click="handleSubmit" :loading="submitting">
                <a-icon type="check" />提交审核
              </a-button>
              <a-button style="margin-left: 8px" @click="handleReset">
                <a-icon type="redo" />重新识别
              </a-button>
            </div>
          </a-form>
        </div>
      </a-card>
    </a-col>
  </a-row>
</template>

<script>
import { post } from '@/api/manage'
import { getToken } from '@/utils/auth'

export default {
  name: "out_order_identify",
  data() {
    return {
      cardStyle: {
        minHeight: 'calc(100vh - 120px)'
      },
      uploadUrl: process.env.VUE_APP_API_BASE_URL + '/ai/bill/recognize',
      headers: {
        'Authorization': 'Bearer ' + getToken()
      },
      fileList: [],
      showResult: false,
      submitting: false,
      supplierList: [],
      columns: [
        {
          title: '商品条码',
          dataIndex: 'barcode',
          width: '20%',
          scopedSlots: { customRender: 'barcode' }
        },
        {
          title: '商品名称',
          dataIndex: 'name',
          width: '25%'
        },
        {
          title: '规格型号',
          dataIndex: 'spec',
          width: '15%'
        },
        {
          title: '数量',
          dataIndex: 'quantity',
          width: '10%'
        },
        {
          title: '单价',
          dataIndex: 'price',
          width: '10%'
        },
        {
          title: '金额',
          dataIndex: 'amount',
          width: '10%'
        },
        {
          title: '操作',
          dataIndex: 'operation',
          scopedSlots: { customRender: 'operation' },
          width: '10%'
        }
      ]
    }
  },
  beforeCreate() {
    this.form = this.$form.createForm(this)
  },
  mounted() {
    this.loadSuppliers()
  },
  methods: {
    beforeUpload(file) {
      // 限制图片大小和类型
      const isImage = file.type.startsWith('image/')
      if (!isImage) {
        this.$message.error('只能上传图片文件!')
        return false
      }
      const isLt5M = file.size / 1024 / 1024 < 5
      if (!isLt5M) {
        this.$message.error('图片大小不能超过5MB!')
        return false
      }
      return true
    },

    handleUploadChange(info) {
      if (info.file.status === 'done') {
        this.$message.success(`${info.file.name} 上传成功`)
        // 设置表单初始值
        const response = info.file.response
        if (response && response.success) {
          this.form.setFieldsValue({
            billNumber: response.data.billNumber,
            supplierId: response.data.supplierId,
            inboundDate: response.data.inboundDate ? this.$moment(response.data.inboundDate) : null,
            items: response.data.items || []
          })
          this.showResult = true
        }
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 上传失败`)
      }
      this.fileList = info.fileList
    },

    loadSuppliers() {
      // 加载供应商列表
      post('/supplier/list', {}).then(res => {
        if (res.code === 200) {
          this.supplierList = res.data
        }
      })
    },

    addItem() {
      const items = this.form.getFieldValue('items') || []
      this.form.setFieldsValue({
        items: [...items, {
          barcode: '',
          name: '',
          spec: '',
          quantity: 1,
          price: 0,
          amount: 0
        }]
      })
    },

    removeItem(index) {
      const items = this.form.getFieldValue('items')
      this.form.setFieldsValue({
        items: items.filter((item, i) => i !== index)
      })
    },

    handleSubmit() {
      this.form.validateFields((err, values) => {
        if (!err) {
          this.submitting = true
          // 提交审核
          post('/inbound/confirm', {
            ...values,
            inboundDate: values.inboundDate ? values.inboundDate.format('YYYY-MM-DD') : null
          }).then(res => {
            if (res.code === 200) {
              this.$message.success('提交成功')
              this.resetForm()
            } else {
              this.$message.error(res.message || '提交失败')
            }
          }).finally(() => {
            this.submitting = false
          })
        }
      })
    },

    handleReset() {
      this.resetForm()
    },

    resetForm() {
      this.form.resetFields()
      this.fileList = []
      this.showResult = false
    }
  }
}
</script>

<style scoped>
.upload-section {
  margin-bottom: 24px;
}

.result-section {
  margin-top: 24px;
}

.table-section {
  margin: 24px 0;
}

.action-buttons {
  margin-top: 24px;
  text-align: center;
}

/* 保持与原有系统一致的卡片样式 */
.ant-card {
  border-radius: 4px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.ant-upload-drag-icon {
  margin-bottom: 16px;
}

.ant-upload-text {
  font-size: 16px;
  color: rgba(0, 0, 0, 0.85);
}

.ant-upload-hint {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
}
</style>